package com.des1gn.ymgetil.util;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;
import com.des1gn.ymgetil.service.ProxyService;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import okhttp3.Authenticator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName HttpUtil
 * @Description TODO
 * @Author Des1gn
 * @Date 2021/11/23 16:21
 * @Version 1.0
 **/
@Slf4j
public class HttpUtil {


    private static Map<String,String> initHeader = new HashMap<>();

    private static List<OkHttpClient> clientList = new ArrayList<>();

    private static  OkHttpClient client = new OkHttpClient().newBuilder()
            .callTimeout(10, TimeUnit.SECONDS)
            .connectTimeout(10,TimeUnit.SECONDS)
            .readTimeout(10,TimeUnit.SECONDS)
            .build();

    static {
        initHeader.put("content-type","application/json");
        initHeader.put("Referer","https://servicewechat.com/wx2c7f0f3c30d99445/91/page-frame.html");
        initHeader.put("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36 MicroMessenger/7.0.9.501 NetType/WIFI MiniProgramEnv/Windows WindowsWechat");
        initHeader.put("zftsl","7d342b9ba70af48142f4943865c1cfd7");
        initHeader.put("host","cloud.cn2030.com");
        initHeader.put("Accept","*/*");
        initHeader.put("Accept-Encoding","gzip, deflate, br");
        initHeader.put("Connection","keep-alive");
    }

    private static OkHttpClient getClient(Proxy proxy){
        if (proxy != null){
            Authenticator proxyAuthenticator = new Authenticator() {
                @Override
                public Request authenticate(Route route, Response response) throws IOException {
                    String credential = Credentials.basic("des1gn", "1132099462ad123");
                    return response.request().newBuilder()
                            .header("Proxy-Authorization", credential)
                            .build();
                }
            };
            OkHttpClient client = new OkHttpClient().newBuilder()
                    .callTimeout(10, TimeUnit.SECONDS)
                    .connectTimeout(10,TimeUnit.SECONDS)
                    .readTimeout(10,TimeUnit.SECONDS)
                    .proxy(proxy)
                    .proxyAuthenticator(proxyAuthenticator)
                    .build();
            return client;
        }else {
            return client;
        }
    }

    public static JSONObject get(String url,String sessionId){
        HttpRequest get = cn.hutool.http.HttpUtil.createGet(url);
        get.setReadTimeout(10000);
        get.setConnectionTimeout(10000);
        get.addHeaders(initHeader);
        get.cookie("ASP.NET_SessionId="+sessionId+"; path=/");
        HttpResponse execute = get.execute();
        if (execute.getStatus() == 200){
            return JSONObject.parseObject(execute.body());
        }
        log.error("http请求错误,{}",execute);
        return null;
    }

    public static JSONObject getCookie(String url,String sessionId){
        HttpRequest get = cn.hutool.http.HttpUtil.createGet(url);
        get.addHeaders(initHeader);
        get.cookie("ASP.NET_SessionId="+sessionId+"; path=/");
        HttpResponse execute = get.execute();
        if (execute.getStatus() == 200){
            JSONObject result = JSONObject.parseObject(execute.body());
            String cookieStr = execute.getCookieStr();
            String substring = cookieStr.substring(cookieStr.indexOf("=")+1, cookieStr.indexOf(";"));
            System.out.println(substring);
            result.put("cookie",substring);
            return result;
        }
        log.error("http请求错误,{}",execute);
        return null;
    }

    public static JSONObject getJdk(String url,String sessionId){
        String result = null;
        try {
            HttpURLConnection urlConnection = (HttpURLConnection)new URL(url).openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.setRequestProperty("content-type","application/json");
            urlConnection.setRequestProperty("Referer","https://servicewechat.com/wx2c7f0f3c30d99445/91/page-frame.html");
            urlConnection.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36 MicroMessenger/7.0.9.501 NetType/WIFI MiniProgramEnv/Windows WindowsWechat");
            urlConnection.setRequestProperty("zftsl","84b8d26942b1b03d41269886ee7d924c");
            urlConnection.setRequestProperty("host","cloud.cn2030.com");
            urlConnection.setRequestProperty("Accept","*/*");
            urlConnection.setRequestProperty("Accept-Encoding","gzip, deflate, br");
            urlConnection.setRequestProperty("Connection","keep-alive");
            urlConnection.setRequestProperty("Cookie","ASP.NET_SessionId="+sessionId+"; path=/");
            urlConnection.connect();
            if (urlConnection.getResponseCode() == 200) {
                InputStream is = urlConnection.getInputStream();
                // 封装输入流is，并指定字符集
                BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                // 存放数据
                StringBuffer sbf = new StringBuffer();
                String temp = null;
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp);
                }
                result = sbf.toString();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (result != null){
            return JSONObject.parseObject(result);
        }
        return null;
    }


    public static JSONObject getOkHttp(String url,String sessionId,Proxy proxy){
        OkHttpClient client = getClient(proxy);
        String result = null;
        Request request = new Request.Builder()
                .url(url)
                .method("GET", null)
                .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36 MicroMessenger/7.0.9.501 NetType/WIFI MiniProgramEnv/Windows WindowsWechat")
                .addHeader("content-type", "application/json")
                .addHeader("Referer", "https://servicewechat.com/wx2c7f0f3c30d99445/91/page-frame.html")
                .addHeader("zftsl", "84b8d26942b1b03d41269886ee7d924c")
                .addHeader("Cookie", "ASP.NET_SessionId="+sessionId+"; path=/")
                .build();
        try {
            Response response = client.newCall(request).execute();
            result = response.body().string();
            log.info("http request : {} , response : {}, proxy:{}",url,result,client.proxy()!=null?client.proxy().toString():null);
            if(StringUtils.isEmpty(result) || result.indexOf("访问异常") > -1){
                return null;
            }
            String cookieStr = response.header("Set-Cookie");
            String substring = null;
            if (!StringUtils.isEmpty(cookieStr)) {
                substring = cookieStr.substring(cookieStr.indexOf("=") + 1, cookieStr.indexOf(";"));
            }
            JSONObject jsonObject = JSONObject.parseObject(result);
            jsonObject.put("cookie",substring);
            return jsonObject;
        } catch (IOException e) {
        }
        return null;
    }

    public static String getOkHttpStr(String url,String sessionId,Proxy proxy){
        OkHttpClient client = getClient(proxy);
        String result = null;
        Request request = new Request.Builder()
                .url(url)
                .method("GET", null)
                .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36 MicroMessenger/7.0.9.501 NetType/WIFI MiniProgramEnv/Windows WindowsWechat")
                .addHeader("content-type", "application/json")
                .addHeader("Referer", "https://servicewechat.com/wx2c7f0f3c30d99445/91/page-frame.html")
                .addHeader("zftsl", "84b8d26942b1b03d41269886ee7d924c")
                .addHeader("Cookie", "ASP.NET_SessionId="+sessionId+"; path=/")
                .build();
        try {
            Response response = client.newCall(request).execute();
            result = response.body().string();
            log.info("http request : {} , response : {}, proxy:{}",url,result,client.proxy()!=null?client.proxy().toString():null);
            if(StringUtils.isEmpty(result) || result.indexOf("访问异常") > -1){
                return null;
            }
            return result;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static JSONObject getOkHttpMiao(String url,String sessionId,Proxy proxy){
        OkHttpClient client = getClient(proxy);
        String result = null;
        Request request = new Request.Builder()
                .url(url)
                .method("GET", null)
                .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36 MicroMessenger/7.0.9.501 NetType/WIFI MiniProgramEnv/Windows WindowsWechat")
                .addHeader("content-type", "application/json")
                .addHeader("tk", sessionId)
                .build();
        try {
            Response response = client.newCall(request).execute();
            result = response.body().string();
            log.info("http request : {} , response : {}, proxy:{}",url,result,client.proxy()!=null?client.proxy().toString():null);
            if(StringUtils.isEmpty(result) || result.indexOf("访问异常") > -1){
                return null;
            }
            JSONObject jsonObject = JSONObject.parseObject(result);
            return jsonObject;
        } catch (IOException e) {
        }
        return null;
    }

    public static JSONObject getOkHttpMiaoSubmit(String url,String sessionId,String sign,Proxy proxy){
        OkHttpClient client = getClient(proxy);
        String result = null;
        Request request = new Request.Builder()
                .url(url)
                .method("GET", null)
                .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36 MicroMessenger/7.0.9.501 NetType/WIFI MiniProgramEnv/Windows WindowsWechat")
                .addHeader("content-type", "application/json")
                .addHeader("tk", sessionId)
                .addHeader("ecc-hs", sign)
                .build();
        try {
            Response response = client.newCall(request).execute();
            result = response.body().string();
            log.info("http request : {} , response : {}, proxy:{}",url,result,client.proxy()!=null?client.proxy().toString():null);
            if(StringUtils.isEmpty(result) || result.indexOf("访问异常") > -1){
                System.out.println("请求失败---"+result);
                return null;
            }
            System.out.println("请求成功---"+result+client.proxy().toString());
            JSONObject jsonObject = JSONObject.parseObject(result);
            return jsonObject;
        } catch (IOException e) {
        }
        return null;
    }


    public static String getStr(String url,String sessionId){
        HttpRequest get = cn.hutool.http.HttpUtil.createGet(url);
        get.addHeaders(initHeader);
        get.cookie("ASP.NET_SessionId="+sessionId);
        HttpResponse execute = get.execute();
        if (execute.getStatus() == 200){
            return execute.body();
        }
        log.error("http请求错误,{}",execute);
        return null;
    }


}
